<template>
	<view class="login">
		<view class="">
			<view class="login-content">
				<view class="login-content-title">登录聚芯食堂</view>
				<LoginBox></LoginBox>

				<!-- #ifdef MP-WEIXIN -->
				<button
					class="wx-login-btn"
					type="primary"
					open-type="getPhoneNumber"
					@getphonenumber="getOpenIdAccessToeknPhoneCode"
				>
					微信一键登录
				</button>
				<!-- #endif -->
			</view>

			<!-- <button
				type="default"
				size="mini"
				@tap="getUserByPhoneOpenId"
			>
				openid
			</button> -->

			<!-- <view>{{ openId }}</view>
			<view>{{ accessToken }}</view> -->
		</view>
	</view>
</template>

<script>
import { useUserStore } from '@/stores/user.js';

import { getUserByOpenId, getUserByPhoneOpenId } from '@/apis/users.js';

export default {
	data() {
		return {
			openId: '',
			accessToken: '',
			phoneCode: '',
		};
	},
	created() {
		// const userStore = useUserStore();
		// if (userStore.checkUser()) {
		// 	uni.redirectTo({
		// 		url: '../../pages/index/index',
		// 	});
		// }
	},
	methods: {
		getOpenIdAccessToeknPhoneCode(e) {
			const that = this;
			const APPID = 'wx04cc1ae564e62510';
			const SECRET = 'd61558a5bbc4727463724a9475669289';
			const phoneCode = e.detail.code;
			this.phoneCode = phoneCode;
			// console.log('e.detail.code', e.detail.code);
			// console.log('phoneCode', phoneCode);

			uni.login({
				provider: 'weixin', //使用微信登录
				success(loginRes) {
					const jsCode = loginRes.code;
					// console.log('jsCode', jsCode);

					// 获取OpenId 调用 code2Session，使用 code 换取 openid、unionid、session_key 等信息
					const code2Session = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${jsCode}&grant_type=authorization_code`;
					const getOpenId = uni.request({ url: code2Session });

					// 获取AccessToken
					const getAccessToken = uni.request({
						url: 'https://api.weixin.qq.com/cgi-bin/token',
						data: {
							grant_type: 'client_credential',
							appid: APPID,
							secret: SECRET,
						},
					});

					// 一起发送请求
					Promise.all([getOpenId, getAccessToken]).then(([openIdRes, accessTokenRes]) => {
						// console.log('openIdRes', openIdRes);
						// console.log('accessTokenRes', accessTokenRes);
						// console.log('openId', openId);
						// console.log('accessToken', accessToken);

						const openId = openIdRes.data.openid;
						const accessToken = accessTokenRes.data.access_token;

						that.openId = openId;
						that.accessToken = accessToken;

						that.getUserInMiniApp();
					});
				},
			});
		},
		async getUserInMiniApp() {
			const openId = this.openId;
			const accessToken = this.accessToken;
			const phoneCode = this.phoneCode;
			const userStore = useUserStore();

			let res = await getUserByOpenId(this.openId);
			// console.log('getUserByOpenId res', res);
			// 用户存在，保存用户
			if (res.data) {
				userStore.saveUser(res.data);
				uni.redirectTo({
					url: '../index/index',
				});
				return;
			}

			// 如果openId没有获取到用户，查询微信api获取手机号
			res = await uni.request({
				url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`,
				method: 'POST',
				data: {
					code: phoneCode,
					openid: openId,
				},
			});
			// console.log('res', res);
			const phoneNumber = res.data?.phone_info?.purePhoneNumber;

			if (!phoneNumber) {
				console.log('出了鬼了');
				return;
			}

			// 通过openId，手机号创建用户
			getUserByPhoneOpenId({
				openId,
				phone: phoneNumber,
			}).then((res) => {
				// console.log('res', res);
				// 保存用户
				userStore.saveUser(res.data);
				uni.redirectTo({
					url: '../index/index',
				});
			});
		},

		// getUserByPhoneOpenId() {
		// 	getUserByPhoneOpenId({
		// 		openId: '222',
		// 		phone: '12311112222',
		// 	}).then((res) => {
		// 		console.log('res', res);
		// 	});
		// },
	},
};
</script>

<style scoped>
.login {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.login-content {
	width: 698rpx;
	margin-top: -128rpx;
	/* margin-top: 128rpx; */
}

.login-content-title {
	margin-bottom: 128rpx;
	font-size: 28px;
}

.wx-login-btn {
	margin-top: 64rpx;
}
</style>
